import cv2
from model import VXSlim
from dataprocess import PreProcess, PostProcess

faceDetected = cv2.CascadeClassifier("assets/haarcascade_frontalface_default.xml")
model=VXSlim("assets/mixVX_48x48_fer2013plus_32bs_43-0.83.hdf5")
prep = PreProcess()
postp = PostProcess()




def getFaceCrop(model, RGB_image):
    """
    检测图像中人脸并经过裁剪后返回
    :param model: 人脸检测模型
    :param RGB_image: 待人脸检测的RGB图像
    :return: 裁剪后的人脸区域灰度图图像：成功(True)或失败(False),人脸区域灰度图，人脸在原图中的坐标
    """
    gray_image = cv2.cvtColor(RGB_image, cv2.COLOR_BGR2GRAY)
    faces = model.detectMultiScale(gray_image, 1.3, 5)

    for face_coordinates in faces:
        x, y, width, height = face_coordinates
        x1, x2, y1, y2 = x, x + width, y, y + height
        gray_face = gray_image[y1:y2, x1:x2]
        return True, gray_face, [(x1, y1), (x2, y2)]
    return False, None, None


cap = cv2.VideoCapture(0)
assert cap.isOpened(), "摄像头未打开"
while True:
    ret, frame = cap.read()
    if ret:
        sign, gray, pos = getFaceCrop(faceDetected, frame)
        if sign:
            res = model(prep(gray))
            label = postp(res)[0]

            cv2.rectangle(frame, pos[0], pos[1], (0, 255, 0), 1)
            cv2.putText(frame, label, pos[0], cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)
        cv2.imshow("", frame)
        key = cv2.waitKey(1)
        if key == "27":
            break
